import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { getInfoApi, toLoginApi, getCaptchaApi } from '../api/info'
import { devtools } from 'zustand/middleware'
// store.ts
type Count = {
    count: number
    menuList: Array<any>
    innerAdd: () => void
    innerClose: () => void
}
const Store = create(
    devtools(
        persist(
            (set, get) => ({
                count: 0,
                menuList: [],
                userInfo: {},
                userId: '',
                innerAdd: () =>
                    set((state: Count) => ({ count: state.count + 1 })),
                innerClose: () =>
                    set((state: Count) => ({ count: state.count - 1 })),
                // 异步获取用户信息
                fetchUserInfo: async () => {
                    const userId = get().userId
                    try {
                        const data = await getInfoApi({ userId })
                        // 这里可以根据返回的数据更新状态
                        set({ menuList: data.data.path || [] })
                        set({ userInfo: data.data.userInfo || {} })
                    } catch (error) {
                        console.error('Failed to fetch user info:', error)
                    }
                },
                // 异步获取验证码
                getCaptcha: async () => {
                    return await new Promise((resolve: any, reject: any) => {
                        getCaptchaApi()
                            .then((res: any) => {
                                resolve(res)
                            })
                            .catch((err) => {
                                reject(err)
                            })
                    })
                },
                // 异步调用登录接口
                toLogin: async (credentials: {
                    username: string
                    password: string
                    captcha: string
                }) => {
                    return await new Promise((resolve: any, reject: any) => {
                        toLoginApi(credentials)
                            .then((res: any) => {
                                // 存储token和用户相关信息
                                localStorage.setItem(
                                    'authToken',
                                    res.data.token
                                )
                                set({ userId: res.data.user.id || '' })
                                resolve(res.data.token)
                            })
                            .catch((err) => {
                                reject(err)
                            })
                    })
                },
                // 退出登录
                toLogout: () => {
                    return new Promise((resolve) => {
                        set({ userInfo: {}, menuList: [] })
                        localStorage.removeItem('authToken')
                        // 重置其他状态，如菜单等
                        localStorage.removeItem('selectedKeys')
                        localStorage.removeItem('openKeys')
                        localStorage.removeItem('breadcrumb')
                        resolve(true)
                    })
                },
            }),
            {
                name: 'food-storage', // unique name
                storage: createJSONStorage(() => sessionStorage), // (optional) by default, 'localStorage' is used
            }
        )
    )
)
export default Store
